<script setup lang="ts">
import { ref, onMounted, computed, h } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  ElMessage,
  ElCard,
  ElButton,
  ElTag,
  ElDescriptions,
  ElDescriptionsItem,
  ElProgress,
  ElDivider,
  ElLink,
  ElCollapse,
  ElCollapseItem,
} from "element-plus";
import { ArrowLeft, ArrowDown, ArrowRight } from "@element-plus/icons-vue";
import { getIntelligenceDetail } from "../servers";

const route = useRoute();
const router = useRouter();

const loading = ref(false);
const intelligenceDetail = ref<any>(null); // 存储完整的data对象
const matches = ref<any[]>([]);
const pocRecommendations = ref<any[]>([]);
const expandedMatches = ref<Set<number>>(new Set()); // 展开的匹配项ID

// 获取情报ID
const intelligenceId = computed(() => route.params.id as string);

// 基本信息computed（从basic_info获取）
const basicInfo = computed(() => {
  return intelligenceDetail.value?.basic_info || null;
});

// 是否已加载数据
const isDataLoaded = computed(() => {
  return !loading.value && intelligenceDetail.value !== null;
});

// 获取危险等级标签类型（支持Unknown）
const getVulLevelTag = (level: string) => {
  const levelMap: Record<string, any> = {
    严重: { text: "严重", type: "danger", color: "#FF4D4F" },
    高危: { text: "高危", type: "danger", color: "#FF7A45" },
    中危: { text: "中危", type: "warning", color: "#FFA940" },
    低危: { text: "低危", type: "info", color: "#52C41A" },
    Unknown: { text: "未知", type: "info", color: "#909399" },
  };
  return (
    levelMap[level] || { text: level || "未知", type: "info", color: "#909399" }
  );
};

// 获取CVSS分数对应的风险等级
const getRiskLevel = (score: number) => {
  if (score >= 9.0) return { level: "严重", color: "#FF4D4F" };
  if (score >= 7.0) return { level: "高危", color: "#FF7A45" };
  if (score >= 4.0) return { level: "中危", color: "#FFA940" };
  return { level: "低危", color: "#52C41A" };
};

// 获取CVSS4进度百分比
const getCvss4Progress = (score: number) => {
  return (score / 10) * 100;
};

// 获取情报详情
const fetchDetail = async () => {
  if (!intelligenceId.value) {
    ElMessage.error("缺少情报ID");
    return;
  }

  loading.value = true;
  try {
    const { data } = await getIntelligenceDetail({
      intelligence_id: intelligenceId.value,
    });

    // 根据实际返回的数据结构处理
    intelligenceDetail.value = data;
    matches.value = data?.matches || [];
    pocRecommendations.value = data?.poc_recommendations || [];
  } catch (error: any) {
    ElMessage.error(error.message || "获取情报详情失败");
    console.error("获取详情失败:", error);
    intelligenceDetail.value = null;
    matches.value = [];
    pocRecommendations.value = [];
  } finally {
    loading.value = false;
  }
};

// 返回列表
const handleBack = () => {
  // 返回到情报管理tab，并保留task参数
  const task = route.query.task;
  router.push({
    name: "VulnerabilityReview",
    query: {
      ...(task ? { task } : {}),
      tab: "1", // 激活情报管理tab
    },
  });
};

// 处理IP点击跳转
const handleIpClick = (ip: string) => {
  if (!ip) return;
  router.push({
    path: "/risk-disposal/ip-detail",
    query: { ip },
  });
};

// 解析匹配原因
const parseMatchReason = (matchReason: string | object) => {
  if (!matchReason) return null;
  try {
    const reason =
      typeof matchReason === "string" ? JSON.parse(matchReason) : matchReason;
    return reason;
  } catch (error) {
    console.error("解析匹配原因失败:", error);
    return null;
  }
};

// 格式化匹配原因（用于 tooltip）
const formatMatchReason = (matchReason: string | object) => {
  const reason = parseMatchReason(matchReason);
  if (!reason) return "无匹配原因";

  const keywords = reason.keywords || {};
  const parts = [];

  if (keywords.products?.length) {
    const productList = keywords.products.slice(0, 10).join(", ");
    const more =
      keywords.products.length > 10 ? `等${keywords.products.length}个` : "";
    parts.push(`产品: ${productList}${more}`);
  }
  if (keywords.services?.length) {
    parts.push(`服务: ${keywords.services.join(", ")}`);
  }
  if (keywords.versions?.length) {
    const versionList = keywords.versions.slice(0, 10).join(", ");
    const more =
      keywords.versions.length > 10 ? `等${keywords.versions.length}个` : "";
    parts.push(`版本: ${versionList}${more}`);
  }
  if (keywords.components?.length) {
    parts.push(`组件: ${keywords.components.join(", ")}`);
  }
  if (keywords.vuln_types?.length) {
    parts.push(`漏洞类型: ${keywords.vuln_types.join(", ")}`);
  }
  if (keywords.frameworks?.length) {
    parts.push(`框架: ${keywords.frameworks.join(", ")}`);
  }
  if (reason.is_suspect !== undefined) {
    parts.push(reason.is_suspect ? "可疑匹配" : "正常匹配");
  }
  if (reason.compliance_asset_id) {
    parts.push(`合规资产ID: ${reason.compliance_asset_id}`);
  }

  return parts.length > 0 ? parts.join("\n") : "匹配成功";
};

// 获取匹配原因摘要（简短版本）
const getMatchReasonSummary = (matchReason: string | object) => {
  const reason = parseMatchReason(matchReason);
  if (!reason) return "无匹配信息";

  const keywords = reason.keywords || {};
  const summary = [];

  if (keywords.products?.length) {
    summary.push(`${keywords.products.length}个产品`);
  }
  if (keywords.services?.length) {
    summary.push(`${keywords.services.length}个服务`);
  }
  if (keywords.versions?.length) {
    summary.push(`${keywords.versions.length}个版本`);
  }
  if (reason.is_suspect) {
    summary.push("可疑");
  }

  return summary.length > 0 ? summary.join(" · ") : "匹配成功";
};

// 切换匹配项展开状态
const toggleMatchExpanded = (matchId: number) => {
  if (expandedMatches.value.has(matchId)) {
    expandedMatches.value.delete(matchId);
  } else {
    expandedMatches.value.add(matchId);
  }
};

// 判断匹配项是否展开
const isMatchExpanded = (matchId: number) => {
  return expandedMatches.value.has(matchId);
};

// 格式化时间显示
const formatTime = (timeStr: string) => {
  if (!timeStr) return "-";
  try {
    const date = new Date(timeStr);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch (error) {
    return timeStr;
  }
};

onMounted(() => {
  fetchDetail();
});
</script>

<template>
  <div v-loading="loading">
    <!-- 返回按钮 -->
    <div style="margin-bottom: 16px">
      <el-button :icon="ArrowLeft" @click="handleBack"> 返回列表 </el-button>
    </div>

    <!-- 顶部标签栏 -->
    <el-card v-if="isDataLoaded" shadow="never" style="margin-bottom: 16px">
      <div style="display: flex; gap: 12px; align-items: center">
        <el-tag v-if="basicInfo?.source" size="large">{{
          basicInfo.source
        }}</el-tag>
        <el-tag
          v-if="basicInfo?.title || basicInfo?.vulnerability_id"
          type="info"
          size="large"
        >
          {{ basicInfo?.title || basicInfo?.vulnerability_id }}
        </el-tag>
        <el-tag
          v-if="basicInfo?.severity"
          :type="getVulLevelTag(basicInfo.severity).type"
          size="large"
        >
          {{ getVulLevelTag(basicInfo.severity).text }}
        </el-tag>
      </div>
    </el-card>

    <!-- 主要内容区域：左右分栏 -->
    <div
      v-if="isDataLoaded"
      style="display: grid; grid-template-columns: 2fr 1fr; gap: 16px"
    >
      <!-- 左列：漏洞描述和信息 -->
      <div>
        <!-- 漏洞标题 -->
        <el-card shadow="never" style="margin-bottom: 16px">
          <h1
            style="
              font-size: 20px;
              font-weight: 600;
              margin: 0;
              line-height: 1.5;
            "
          >
            {{ basicInfo?.title || basicInfo?.vulnerability_id || "N/A" }}
          </h1>
          <div
            v-if="basicInfo?.vulnerability_id"
            style="margin-top: 8px; color: #909399; font-size: 14px"
          >
            {{ basicInfo.vulnerability_id }}
          </div>
        </el-card>

        <!-- 关键信息 -->
        <el-card shadow="never" style="margin-bottom: 16px">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="漏洞ID">
              {{
                basicInfo?.vulnerability_id ||
                basicInfo?.intelligence_id ||
                "N/A"
              }}
            </el-descriptions-item>
            <el-descriptions-item label="严重程度">
              <el-tag
                :type="getVulLevelTag(basicInfo?.severity || '').type"
                size="small"
              >
                {{ getVulLevelTag(basicInfo?.severity || "").text }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="发布时间">
              {{ basicInfo?.publish_date || basicInfo?.created_time || "N/A" }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag
                :type="basicInfo?.is_active ? 'success' : 'info'"
                size="small"
              >
                {{ basicInfo?.is_active ? "活跃" : "非活跃" }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 漏洞描述 -->
        <el-card shadow="never" style="margin-bottom: 16px">
          <div style="font-weight: 600; margin-bottom: 12px; font-size: 16px">
            漏洞描述
          </div>
          <div
            style="
              color: #606266;
              line-height: 1.8;
              white-space: pre-wrap;
              word-break: break-word;
            "
          >
            {{ basicInfo?.description || "暂无描述" }}
          </div>
        </el-card>

        <!-- 匹配资产信息 -->
        <el-card
          v-if="matches.length > 0"
          shadow="never"
          style="margin-bottom: 16px"
        >
          <div style="font-weight: 600; margin-bottom: 12px; font-size: 16px">
            匹配资产 ({{ matches.length }})
          </div>
          <div style="color: #606266; line-height: 1.8">
            <div
              v-for="(match, index) in matches"
              :key="match.id || index"
              style="
                margin-bottom: 12px;
                padding: 12px;
                background: #f8f9fa;
                border-radius: 4px;
                border-left: 3px solid #409eff;
              "
            >
              <div
                style="
                  display: flex;
                  align-items: center;
                  gap: 12px;
                  flex-wrap: wrap;
                "
              >
                <div>
                  <el-link
                    type="primary"
                    :underline="false"
                    style="cursor: pointer; font-weight: 500; font-size: 14px"
                    @click="handleIpClick(match.asset_ip)"
                  >
                    {{ match.asset_ip }}
                  </el-link>
                  <span
                    v-if="match.asset_port"
                    style="margin-left: 8px; color: #909399; font-size: 12px"
                  >
                    :{{ match.asset_port }}
                  </span>
                </div>
                <el-tag
                  v-if="match.match_confidence !== undefined"
                  type="success"
                  size="small"
                >
                  置信度: {{ (match.match_confidence * 100).toFixed(1) }}%
                </el-tag>
                <el-tag
                  v-if="match.match_reason"
                  :type="
                    parseMatchReason(match.match_reason)?.is_suspect
                      ? 'warning'
                      : 'info'
                  "
                  size="small"
                  style="cursor: help"
                  :title="formatMatchReason(match.match_reason)"
                >
                  {{ getMatchReasonSummary(match.match_reason) }}
                </el-tag>
              </div>
              <div
                v-if="match.created_time"
                style="margin-top: 4px; color: #909399; font-size: 12px"
              >
                匹配时间: {{ formatTime(match.created_time) }}
              </div>

              <!-- 匹配详情展开 -->
              <div
                v-if="
                  match.match_reason && parseMatchReason(match.match_reason)
                "
                style="margin-top: 8px"
              >
                <el-button
                  text
                  type="primary"
                  size="small"
                  @click="toggleMatchExpanded(match.id)"
                  style="padding: 0; height: auto"
                >
                  <el-icon
                    :style="{
                      transform: isMatchExpanded(match.id)
                        ? 'rotate(90deg)'
                        : 'rotate(0deg)',
                      transition: 'transform 0.2s',
                    }"
                  >
                    <ArrowRight />
                  </el-icon>
                  <span style="margin-left: 4px">
                    {{ isMatchExpanded(match.id) ? "收起详情" : "查看详情" }}
                  </span>
                </el-button>

                <div
                  v-if="isMatchExpanded(match.id)"
                  style="
                    margin-top: 8px;
                    padding: 12px;
                    background: #ffffff;
                    border: 1px solid #e4e7ed;
                    border-radius: 4px;
                    font-size: 12px;
                  "
                >
                  <template v-if="parseMatchReason(match.match_reason)">
                    <div
                      v-if="
                        parseMatchReason(match.match_reason)?.keywords?.products
                          ?.length
                      "
                      style="margin-bottom: 8px"
                    >
                      <strong style="color: #606266">产品:</strong>
                      <div style="margin-top: 4px">
                        <el-tag
                          v-for="(product, idx) in parseMatchReason(
                            match.match_reason
                          ).keywords.products"
                          :key="idx"
                          size="small"
                          type="info"
                          style="margin-right: 4px; margin-bottom: 4px"
                        >
                          {{ product }}
                        </el-tag>
                      </div>
                    </div>
                    <div
                      v-if="
                        parseMatchReason(match.match_reason)?.keywords?.services
                          ?.length
                      "
                      style="margin-bottom: 8px"
                    >
                      <strong style="color: #606266">服务:</strong>
                      <div style="margin-top: 4px">
                        <el-tag
                          v-for="(service, idx) in parseMatchReason(
                            match.match_reason
                          ).keywords.services"
                          :key="idx"
                          size="small"
                          type="success"
                          style="margin-right: 4px; margin-bottom: 4px"
                        >
                          {{ service }}
                        </el-tag>
                      </div>
                    </div>
                    <div
                      v-if="
                        parseMatchReason(match.match_reason)?.keywords?.versions
                          ?.length
                      "
                      style="margin-bottom: 8px"
                    >
                      <strong style="color: #606266">版本:</strong>
                      <div style="margin-top: 4px">
                        <el-tag
                          v-for="(version, idx) in parseMatchReason(
                            match.match_reason
                          ).keywords.versions"
                          :key="idx"
                          size="small"
                          type="warning"
                          style="margin-right: 4px; margin-bottom: 4px"
                        >
                          {{ version }}
                        </el-tag>
                      </div>
                    </div>
                    <div
                      v-if="
                        parseMatchReason(match.match_reason)?.keywords
                          ?.components?.length
                      "
                      style="margin-bottom: 8px"
                    >
                      <strong style="color: #606266">组件:</strong>
                      <div style="margin-top: 4px">
                        <el-tag
                          v-for="(component, idx) in parseMatchReason(
                            match.match_reason
                          ).keywords.components"
                          :key="idx"
                          size="small"
                          style="margin-right: 4px; margin-bottom: 4px"
                        >
                          {{ component }}
                        </el-tag>
                      </div>
                    </div>
                    <div
                      v-if="
                        parseMatchReason(match.match_reason)?.keywords
                          ?.vuln_types?.length
                      "
                      style="margin-bottom: 8px"
                    >
                      <strong style="color: #606266">漏洞类型:</strong>
                      <div style="margin-top: 4px">
                        <el-tag
                          v-for="(vulnType, idx) in parseMatchReason(
                            match.match_reason
                          ).keywords.vuln_types"
                          :key="idx"
                          size="small"
                          type="danger"
                          style="margin-right: 4px; margin-bottom: 4px"
                        >
                          {{ vulnType }}
                        </el-tag>
                      </div>
                    </div>
                    <div
                      v-if="
                        parseMatchReason(match.match_reason)?.is_suspect !==
                        undefined
                      "
                      style="margin-bottom: 8px"
                    >
                      <strong style="color: #606266">匹配类型:</strong>
                      <el-tag
                        :type="
                          parseMatchReason(match.match_reason)?.is_suspect
                            ? 'warning'
                            : 'success'
                        "
                        size="small"
                        style="margin-left: 8px"
                      >
                        {{
                          parseMatchReason(match.match_reason)?.is_suspect
                            ? "可疑匹配"
                            : "正常匹配"
                        }}
                      </el-tag>
                    </div>
                    <div
                      v-if="
                        parseMatchReason(match.match_reason)
                          ?.compliance_asset_id
                      "
                      style="margin-bottom: 8px"
                    >
                      <strong style="color: #606266">合规资产ID:</strong>
                      <span style="margin-left: 8px">
                        {{
                          parseMatchReason(match.match_reason)
                            ?.compliance_asset_id
                        }}
                      </span>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- POC推荐 -->
        <el-card
          v-if="pocRecommendations.length > 0"
          shadow="never"
          style="margin-bottom: 16px"
        >
          <div style="font-weight: 600; margin-bottom: 12px; font-size: 16px">
            POC推荐 ({{ pocRecommendations.length }})
          </div>
          <div style="color: #606266; line-height: 1.8">
            <div
              v-for="(poc, index) in pocRecommendations"
              :key="index"
              style="margin-bottom: 8px"
            >
              <el-tag type="warning" size="small">{{
                poc.poc_name || poc.poc_id || `POC ${index + 1}`
              }}</el-tag>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右列：CVSS评分和技术信息 -->
      <div>
        <!-- CVSS评分 -->
        <el-card shadow="never" style="margin-bottom: 16px">
          <div style="font-weight: 600; margin-bottom: 12px; font-size: 16px">
            CVSS评分
          </div>
          <div v-if="basicInfo?.cvss_score" style="text-align: center">
            <div
              style="
                font-size: 48px;
                font-weight: bold;
                color: #303133;
                margin-bottom: 16px;
              "
            >
              {{ basicInfo.cvss_score }}
            </div>
            <el-tag
              :type="
                getRiskLevel(parseFloat(basicInfo.cvss_score)).level ===
                  '严重' ||
                getRiskLevel(parseFloat(basicInfo.cvss_score)).level === '高危'
                  ? 'danger'
                  : getRiskLevel(parseFloat(basicInfo.cvss_score)).level ===
                    '中危'
                  ? 'warning'
                  : 'success'
              "
              size="large"
              style="margin-bottom: 12px"
            >
              {{ getRiskLevel(parseFloat(basicInfo.cvss_score)).level }}
            </el-tag>
            <el-progress
              :percentage="getCvss4Progress(parseFloat(basicInfo.cvss_score))"
              :color="getRiskLevel(parseFloat(basicInfo.cvss_score)).color"
              :stroke-width="12"
              :show-text="false"
            />
          </div>
          <div v-else style="text-align: center; color: #909399">暂无评分</div>
        </el-card>

        <!-- 其他信息 -->
        <el-card shadow="never">
          <div style="font-weight: 600; margin-bottom: 12px; font-size: 16px">
            其他信息
          </div>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="情报来源">
              {{ basicInfo?.source || "N/A" }}
            </el-descriptions-item>
            <el-descriptions-item label="情报ID">
              {{ basicInfo?.intelligence_id || basicInfo?.id || "N/A" }}
            </el-descriptions-item>
            <el-descriptions-item label="漏洞ID">
              {{ basicInfo?.vulnerability_id || "N/A" }}
            </el-descriptions-item>
            <el-descriptions-item label="匹配数量">
              {{ matches.length || 0 }}
            </el-descriptions-item>
            <el-descriptions-item label="POC推荐数">
              {{ pocRecommendations.length || 0 }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ basicInfo?.created_time || "N/A" }}
            </el-descriptions-item>
            <el-descriptions-item label="发布时间">
              {{ basicInfo?.publish_date || "N/A" }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag
                :type="basicInfo?.is_active ? 'success' : 'info'"
                size="small"
              >
                {{ basicInfo?.is_active ? "活跃" : "非活跃" }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-card) {
  border-radius: 4px;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}
</style>
